# @Time : 2025/4/19 17:25
# @Author : ZhangQi
# gui_main.py
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import threading
import json
from adb.device_manager import DeviceManager
from config import DEVICES_ID


class ADBGUIApp:
    def __init__(self, root):
        self.root = root
        self.device_manager = None
        self.setup_ui()
        self.connect_device()

    def setup_ui(self):
        """初始化界面组件"""
        self.root.title("ADB智能控制助手 v1.0")
        self.root.geometry("800x600")

        # 设备状态栏
        self.status_frame = ttk.Frame(self.root)
        self.status_frame.pack(pady=10, fill=tk.X)

        self.status_label = ttk.Label(
            self.status_frame,
            text="设备状态：未连接",
            foreground="red"
        )
        self.status_label.pack(side=tk.LEFT, padx=10)

        # 指令输入区域
        self.input_frame = ttk.Frame(self.root)
        self.input_frame.pack(pady=10, fill=tk.X)

        self.cmd_entry = ttk.Entry(self.input_frame, width=70)
        self.cmd_entry.pack(side=tk.LEFT, padx=5)
        self.cmd_entry.bind("<Return>", lambda e: self.execute_command())

        self.send_btn = ttk.Button(
            self.input_frame,
            text="发送指令",
            command=self.execute_command
        )
        self.send_btn.pack(side=tk.LEFT)

        # 结果展示区域
        self.result_area = scrolledtext.ScrolledText(
            self.root,
            wrap=tk.WORD,
            font=('Consolas', 10)
        )
        self.result_area.pack(pady=10, fill=tk.BOTH, expand=True)
        self.result_area.tag_config('success', foreground='green')
        self.result_area.tag_config('error', foreground='red')

        # 历史记录
        self.history_listbox = tk.Listbox(self.root, height=5)
        self.history_listbox.pack(fill=tk.X, pady=5)
        self.history_listbox.bind("<<ListboxSelect>>", self.load_history)

    def connect_device(self):
        """连接设备后台任务"""

        def _connect():
            try:
                self.device_manager = DeviceManager(device_id=DEVICES_ID.get("device_id"))
                self.update_status("设备已连接", "green")
                self.append_result("✅ 设备连接成功！\n支持指令示例：\n"
                                   "1. 点击登录按钮\n"
                                   "2. 输入用户名test\n"
                                   "3. 滑动[100,200]->[300,400]\n"
                                   "4. 执行淘宝的Monkey测试500次")
            except Exception as e:
                self.update_status(f"连接失败: {str(e)}", "red")
                messagebox.showerror("连接错误", f"无法连接设备: {str(e)}")

        threading.Thread(target=_connect, daemon=True).start()

    def execute_command(self):
        """执行指令"""
        command = self.cmd_entry.get().strip()
        if not command:
            messagebox.showwarning("输入错误", "指令不能为空")
            return

        self.add_history(command)
        self.cmd_entry.delete(0, tk.END)
        self.append_result(f"\n🔧 执行指令: {command}", clear_tags=False)

        def _execute():
            try:
                result = self.device_manager.process_command(command)
                formatted = json.dumps(result, indent=2, ensure_ascii=False)
                self.append_result(f"\n✅ 执行成功:\n{formatted}", 'success')
            except Exception as e:
                self.append_result(f"\n❌ 执行失败: {str(e)}", 'error')

        threading.Thread(target=_execute, daemon=True).start()

    def update_status(self, text, color):
        """更新状态栏"""
        self.status_label.config(text=f"设备状态：{text}", foreground=color)

    def append_result(self, text, tag=None, clear_tags=False):
        """追加结果显示"""
        self.result_area.config(state=tk.NORMAL)
        if clear_tags:
            self.result_area.delete(1.0, tk.END)
        self.result_area.insert(tk.END, text + "\n", tag)
        self.result_area.see(tk.END)
        self.result_area.config(state=tk.DISABLED)

    def add_history(self, command):
        """添加历史记录"""
        self.history_listbox.insert(0, command)
        if self.history_listbox.size() > 10:
            self.history_listbox.delete(10, tk.END)

    def load_history(self, event):
        """加载历史记录到输入框"""
        selection = self.history_listbox.curselection()
        if selection:
            self.cmd_entry.delete(0, tk.END)
            self.cmd_entry.insert(0, self.history_listbox.get(selection[0]))


if __name__ == "__main__":
    root = tk.Tk()
    app = ADBGUIApp(root)

    # 设置窗口图标（需要准备ico文件）
    try:
        root.iconbitmap('adb_icon.ico')
    except:
        pass

    root.mainloop()